package com.youmu.maven.emall.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.youmu.maven.emall.dao.PermissionDao;
import com.youmu.maven.emall.dao.RoleDao;
import com.youmu.maven.emall.entity.Role;
import com.youmu.maven.emall.service.IRoleService;
import com.youmu.maven.emall.service.support.BaseService;

@Service
public class RoleService extends BaseService implements IRoleService {
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private PermissionDao permissionDao;

	@Override
	public Page<Role> queryRole(Role role, int page, int rows) {
		PageHelper.startPage(page, rows);
		Map<String, Object> map = initParam(role);
		return roleDao.getRolesByPage(map);
	}

	@Override
	public List<Role> queryRoleFull(Role role) {
		List<Role> roles = roleDao.getRoles(initParam(role));
		for (Role r : roles) {
			fullRole(r);
		}
		return roles;
	}

	public void fullRole(Role role) {
		role.setPermissions(permissionDao.getPermissionsByRoleId(role.getId()));
	}

	public Set<Role> queryRoleByUserId(Long userId) {
		Set<Role> roles = roleDao.getRoleByUserId(userId);
		for (Role role : roles) {
			fullRole(role);
		}
		return roles;
	}

	@Override
	public Role queryRoleFullById(Long id, boolean throwException) {
		Role role = new Role();
		role.setId(id);
		Map<String, Object> map = initParam(role);
		List<Role> list = roleDao.getRoles(map);
		role = (Role) getOne(list, throwException);
		if (role == null) {
			return null;
		}
		fullRole(role);
		return role;
	}

	@Override
	public void deleteRoleById(Long id) {
		if (id == null)
			throw new RuntimeException("Null id to delete");
		Role role = new Role();
		role.setId(id);
		roleDao.deleteRole(initParam(role));
	}

	@Override
	public Long insertRole(Role role) {
		return roleDao.insertRole(initParam(role));
	}

	@Override
	public void updateRole(Role role) {
		if (role.getId() == null)
			throw new RuntimeException("Null id to update");
		roleDao.updateRole(initParam(role));
	}
}
